package main

import (
	"fmt"
	"net"
	"strings"
	"sync"
)

type message struct {
	data  string
	quit  chan int
	mutex *sync.Mutex
}

func (msg *message) send_msg(conn net.Conn) {
	for {
		fmt.Printf("client:")

		msg.mutex.Lock()
		msg.data = "" //输入发送的内容
		fmt.Scanln(&msg.data)
		send_buf := []byte(msg.data)
		msg.mutex.Unlock()

		_, err := conn.Write(send_buf) //向服务器发送数据
		if err != nil {
			fmt.Println(err)
			continue //发送出现错误，继续
		}
	}
}

func (msg *message) recv_msg(conn net.Conn) {

	for !strings.EqualFold(msg.data, "Quit") { //收到Quit时退出
		recv_buf := make([]byte, 1024)
		lenght, err := conn.Read(recv_buf[0:]) //接受客户端数据
		if err != nil {
			break
		}
		msg.mutex.Lock() //这样加锁，其实不好的，因为for循环中还在用msg.data
		msg.data = ""
		msg.data = string(recv_buf[0:lenght]) //这里若不用lenght，取到的data长度将会是1024
		fmt.Printf("\rserver:%s", msg.data)   //服务器发送的内容
		msg.mutex.Unlock()

		fmt.Printf("\rclient:")
	}
	conn.Close()
	msg.quit <- 0
	fmt.Println("server is disconnected")
}

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:9005") //连接服务器
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("If you want to exit,please input Quit")

	msg := &message{data: "", quit: make(chan int), mutex: new(sync.Mutex)}
	go func() { msg.send_msg(conn) }()
	go func() { msg.recv_msg(conn) }()
	<-msg.quit
}
